/**
 * Created by yuyangyang on 2015/1/13.
 */
'use strict';
module.exports = function (grunt) {


    var path = require('path'),
        crc32 = require('buffer-crc32'),
        chalk = require('chalk');

    grunt.registerMultiTask('modules', 'modules files.', function () {
        var options = this.options();
        var configStr = grunt.file.read(options.configBuildPath);
        configStr = configStr.trim().replace(/var\s*require\s*=\s*/gi, '');
        var configJson = (new Function('return ' + configStr + ';'))();

        if (!configJson.bundles) {
            configJson.bundles = {};
        }

        this.files.forEach(function (file) {
            var src = file.src.toString(),
                extname = path.extname(src),
                basename = path.basename(src, extname),
                content = grunt.file.read(src),
                signature = crc32.unsigned(content).toString(16);

            options.moduleJson.forEach(function (module) {
                if (module.name === basename) {
                    configJson.bundles[basename + '-' + signature] = module.include;
                    grunt.file.write(path.join(file.orig.dest, basename + '-' + signature + extname), content);
                    grunt.log.writeln(chalk.cyan(basename + '-' + signature) + ': ' + chalk.cyan(module.include));
                }
            });

        });

        grunt.file.write(options.configBuildPath, 'var require=' + JSON.stringify(configJson));
    });
}